package generics;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

public class GenericUtils {

    /**
     * Adds all elements form the array to Collection if the lowest
     * common super class of all Collection elements is a super
     * class array type.
     */
    static void fromArrayToCollection(Object[] a, Collection c){
        Class arrayComponent = a.getClass().getComponentType();
        Class collectionComponent = CollectionTypeGuesser.guessElementType(c);
        if(!collectionComponent.isAssignableFrom(arrayComponent))
            return;
        for(Object o : a){
            c.add(collectionComponent.cast(o));
        }
    }

    static <T> void copyAll(List<? extends T> from, List<? super T> to){
        if(to.size() < from.size())
            throw new IndexOutOfBoundsException("Not enough space in destination collection");

        for(int i = 0; i < from.size(); i++){
            to.set(i, from.get(i));
        }
    }

    static <T extends Comparable> List greaterThan(List<? extends T> collection, T t){
        Class implementation = collection.getClass();
        List result = null;
        try {
            result = (List) implementation.newInstance();
            for(T curr : collection){
                if(curr.compareTo(t) > 0){
                    result.add(curr);
                }
            }
        }
        catch(InstantiationException e) {
            System.out.println(e.toString());
        }
        catch(IllegalAccessException e) {
            System.out.println(e.toString());
        }
        return result;
    }

    public static void main(String[] str){
        Object[] as = new Object[6];
        for(int i = 0; i < 3; i+=2){
            as[i] = new A();
            as[i + 1] = new B();
        }
        ArrayList<Object> bs = new ArrayList<Object>();
        bs.add(new B());
        bs.add(new A());
        fromArrayToCollection(as, bs);
        System.out.println(bs);

        List<Fruit> fr = new ArrayList<Fruit>();
        List<Apple> app = new ArrayList<Apple>();
        List<Orange> or = new ArrayList<Orange>();
        List<RedApple> rapp = new ArrayList<RedApple>();
        List<Melon> mel = new ArrayList<Melon>();

        copyAll(or, fr);
        copyAll(rapp, fr);
        copyAll(rapp, app);
        copyAll(rapp, rapp);
        //copyAll(fr, or);

        List<Integer> list = new ArrayList<Integer>();
        list.add(new Integer(2));
        list.add(new Integer(3));
        list.add(new Integer(1));
        list.add(new Integer(5));
        list.add(new Integer(4));

        List res = greaterThan(list, new Integer(3));
        System.out.println(res);
    }
}

class A{}
class B{}
class Fruit{}
class Apple extends Fruit{}
class Orange extends Fruit{}
class RedApple extends Apple{}
class Melon extends Orange{}
